package com;

import java.io.IOException;
import java.lang.management.ManagementFactory;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;

import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;

public class Foo {

	/**
	 * @param args
	 * @throws NullPointerException 
	 * @throws MalformedObjectNameException 
	 * @throws NotCompliantMBeanException 
	 * @throws MBeanRegistrationException 
	 * @throws InstanceAlreadyExistsException 
	 * @throws InterruptedException 
	 * @throws AttachNotSupportedException 
	 * @throws AgentInitializationException 
	 * @throws AgentLoadException 
	 */
	public static void main(String[] args) throws MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, InterruptedException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {
		Test a = new Test();
		MBeanServer server = ManagementFactory.getPlatformMBeanServer();
		
		ObjectName oName = new ObjectName("demo:aa=a");
		server.registerMBean(a, oName);
		
//		for (int i = 0; i < 20; i++) {
//			Thread.currentThread().sleep(1000);
//			System.out.println(a.getName() + i);
//			
//		}
//		
		try {
			System.in.read();
//			System.out.println(System.getProperties().toString());
			VirtualMachine vmM =null;
//			for (VirtualMachineDescriptor vm : VirtualMachine.list()) {
//				System.out.println(vm.displayName());
//				if (vm.displayName().equals("com.Demo")) {
					vmM = VirtualMachine.attach("8052");
//				}
//			}
			
			
			vmM.loadAgent("TestAgent.jar","change thing");
			Thread.sleep(5000);
			
			vmM.detach();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
